import { ChangePhone, SendUserCode } from "@/api";

let codeMaxSecond = 0;
let codeInterval = null;

export const useContent = () => {
    const dialogVisible = ref(false);
    const userStore = useUserStore();
    const router = useRouter();
    const form = ref({
        code: "",
        password: "",
        old_mobile: "",
        new_mobile: "",
    });
    const codeText = ref("获取验证码");

    const onSendCodeSuccess = () => {
        const _func = () => {
            if (codeMaxSecond === 0) {
                codeText.value = `获取验证码`;
                clearInterval(codeInterval);
            } else {
                codeText.value = `${codeMaxSecond--}s`;
            }
        };
        codeMaxSecond = 120;
        codeInterval = setInterval(_func, 1000);
        _func();
    };

    const onSendCode = async () => {
        if (codeMaxSecond > 0) return;
        if (isPhone(form.value.new_mobile)) {
            const res = await SendUserCode({
                phone: form.value.new_mobile,
                event: "changemobile",
            });

            if (res.code == 200) {
                Message().success("发送成功");
                onSendCodeSuccess();
            } else {
                Message().error(res.msg);
            }
        } else {
            Message().warning("请输入正确的手机号");
        }
    };

    const onSubmit = async (done) => {
        if (isEmpty(form.value.old_mobile)) {
            Message().warning("请输入旧的手机号");
            return false;
        }

        if (!isPhone(form.value.old_mobile)) {
            Message().warning("旧的手机号格式错误");
            return false;
        }

        if (isEmpty(form.value.password)) {
            Message().warning("请输入密码");
            return false;
        }

        if (isEmpty(form.value.new_mobile)) {
            Message().warning("请输入新的手机号");
            return false;
        }

        if (!isPhone(form.value.new_mobile)) {
            Message().warning("新的手机号格式错误");
            return false;
        }

        if (isEmpty(form.value.code)) {
            Message().warning("请输入验证码");
            return false;
        }

        const res = await ChangePhone({
            old_mobile: form.value.old_mobile,
            new_mobile: form.value.new_mobile,
            password: form.value.password,
            code: form.value.code,
        });

        if (res.code == 200) {
            Message().success("修改成功");
            dialogVisible.value = false;
            userStore.CLEAR_USERINFO();
            navigateTo("/login.html");
            typeof done === "function" && done();
        } else {
            Message().error(res.msg);
        }
    };

    return {
        dialogVisible,
        form,
        codeText,
        onSendCode,
        onSubmit,
    };
};
